<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <span>我的考试</span>
      </div>
      
      <!-- 搜索栏 -->
      <el-form :inline="true" :model="queryParams" class="demo-form-inline" size="small">
        <el-form-item label="学科">
          <el-select v-model="queryParams.subjectId" placeholder="请选择学科" clearable filterable>
            <el-option
              v-for="item in subjectOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="状态">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable>
            <el-option label="未开始" :value="0"></el-option>
            <el-option label="进行中" :value="1"></el-option>
            <el-option label="已结束" :value="2"></el-option>
          </el-select>
        </el-form-item>
        
        <el-form-item label="关键词">
          <el-input v-model="queryParams.keyword" placeholder="请输入关键词" clearable></el-input>
        </el-form-item>
        
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
      
      <!-- 考试列表 -->
      <el-tabs v-model="activeTab" @tab-click="handleTabClick">
        <el-tab-pane label="待考试" name="upcoming">
          <el-table
            v-loading="loading"
            :data="examList"
            style="width: 100%"
            border>
            <el-table-column
              prop="title"
              label="考试标题"
              min-width="200">
            </el-table-column>
            
            <el-table-column
              prop="subjectName"
              label="学科"
              width="100"
              align="center">
            </el-table-column>
            
            <el-table-column
              label="考试时间"
              width="260"
              align="center">
              <template slot-scope="scope">
                <div>开始：{{ formatDateTime(scope.row.startTime) }}</div>
                <div>结束：{{ formatDateTime(scope.row.endTime) }}</div>
              </template>
            </el-table-column>
            
            <el-table-column
              prop="duration"
              label="时长(分钟)"
              width="100"
              align="center">
            </el-table-column>
            
            <el-table-column
              prop="statusName"
              label="状态"
              width="100"
              align="center">
              <template slot-scope="scope">
                <el-tag :type="getStatusType(scope.row.status)">
                  {{ scope.row.statusName }}
                </el-tag>
              </template>
            </el-table-column>
            
            <el-table-column
              label="操作"
              width="150"
              align="center">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  @click="viewExam(scope.row)">
                  查看详情
                </el-button>
                <el-button
                  size="mini"
                  type="text"
                  @click="takeExam(scope.row)"
                  v-if="scope.row.status === 1 && !scope.row.hasSubmitted">
                  参加考试
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        
        <el-tab-pane label="已完成" name="completed">
          <el-table
            v-loading="loading"
            :data="examList"
            style="width: 100%"
            border>
            <el-table-column
              prop="title"
              label="考试标题"
              min-width="200">
            </el-table-column>
            
            <el-table-column
              prop="subjectName"
              label="学科"
              width="100"
              align="center">
            </el-table-column>
            
            <el-table-column
              label="考试时间"
              width="260"
              align="center">
              <template slot-scope="scope">
                <div>开始：{{ formatDateTime(scope.row.startTime) }}</div>
                <div>结束：{{ formatDateTime(scope.row.endTime) }}</div>
              </template>
            </el-table-column>
            
            <el-table-column
              prop="score"
              label="得分"
              width="100"
              align="center">
              <template slot-scope="scope">
                {{ scope.row.hasSubmitted ? (scope.row.score + '/' + scope.row.totalScore) : '-' }}
              </template>
            </el-table-column>
            
            <el-table-column
              label="提交时间"
              width="160"
              align="center">
              <template slot-scope="scope">
                {{ scope.row.hasSubmitted ? formatDateTime(scope.row.submitTime) : '-' }}
              </template>
            </el-table-column>
            
            <el-table-column
              label="操作"
              width="150"
              align="center">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  @click="viewResult(scope.row)"
                  v-if="scope.row.hasSubmitted">
                  查看成绩
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          background
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
          :current-page="queryParams.page"
          :page-sizes="[10, 20, 50, 100]"
          :page-size="queryParams.size"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-card>
  </div>
</template>

<script>
import { getExamList } from '@/api/exam';
import { getAllSubjects } from '@/api/subject';

export default {
  name: 'StudentExams',
  data() {
    return {
      loading: false,
      activeTab: 'upcoming',
      examList: [],
      total: 0,
      queryParams: {
        page: 1,
        size: 10,
        subjectId: undefined,
        status: undefined,
        completed: false,
        keyword: ''
      },
      subjectOptions: []
    };
  },
  created() {
    this.getSubjects();
    this.getList();
  },
  methods: {
    // 获取学科列表
    getSubjects() {
      getAllSubjects().then(response => {
        this.subjectOptions = response.data.map(subject => ({
          value: subject.id,
          label: subject.name
        }));
      });
    },
    // 获取考试列表
    getList() {
      this.loading = true;
      
      // 根据当前标签设置查询参数
      this.queryParams.completed = this.activeTab === 'completed';
      
      getExamList(this.queryParams).then(response => {
        this.examList = response.data.records;
        this.total = response.data.total;
        this.loading = false;
      }).catch(() => {
        this.loading = false;
      });
    },
    // 标签切换事件
    handleTabClick() {
      this.queryParams.page = 1;
      this.getList();
    },
    // 查询按钮点击事件
    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },
    // 重置按钮点击事件
    resetQuery() {
      this.queryParams = {
        page: 1,
        size: 10,
        subjectId: undefined,
        status: undefined,
        completed: this.activeTab === 'completed',
        keyword: ''
      };
      this.getList();
    },
    // 每页条数改变时触发
    handleSizeChange(size) {
      this.queryParams.size = size;
      this.getList();
    },
    // 当前页改变时触发
    handleCurrentChange(page) {
      this.queryParams.page = page;
      this.getList();
    },
    // 查看考试详情
    viewExam(row) {
      this.$router.push(`/student/exam/${row.id}`);
    },
    // 参加考试
    takeExam(row) {
      this.$router.push(`/student/exam/take/${row.id}`);
    },
    // 查看考试结果
    viewResult(row) {
      this.$router.push(`/student/exam/result/${row.resultId}`);
    },
    // 格式化日期时间
    formatDateTime(dateTime) {
      if (!dateTime) return '';
      const date = new Date(dateTime);
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      return `${year}-${month}-${day} ${hours}:${minutes}`;
    },
    // 获取状态标签类型
    getStatusType(status) {
      switch (status) {
        case 0: return 'info';
        case 1: return 'success';
        case 2: return 'warning';
        default: return '';
      }
    }
  }
};
</script>

<style scoped>
.pagination-container {
  margin-top: 20px;
  text-align: right;
}
</style> 